package cn.life.common.push.jg;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import cn.life.common.entity.vo.PushVo;
import cn.life.common.push.ios.IosPushConfig;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;
import java.util.List;

/**
 * @Description:
 *
 * @Author 李佳明
 * @Date 2018-09-06 14:37
 */
@Configuration
@PropertySource({"classpath:config.properties"})
public class JgPush {

    @Autowired
    private Environment env;

    /**
     * android推送方法
     * @param pushVo    messageType推送类型0表示透传消息,1表示通知,默认为0.
     * @param
     * @throws APIRequestException
     * @throws APIConnectionException
     */
    public void androidPush(PushVo pushVo) throws APIConnectionException, APIRequestException, IOException {
        //1.赋值
        String title = pushVo.getTitle();
        JSONObject args = pushVo.getExtra();
        Integer messageType = pushVo.getMessageType();
        List<String> tokenList = pushVo.getUserList();
        //2.获取配置信息
        //获取Bean信息
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        JgPushConfig jgPushConfig = (JgPushConfig) wac.getBean("jgPushConfig");

        String appKey = jgPushConfig.getAppKey();
        String secretKey = jgPushConfig.getSecretKey();

        PushPayload payload=null;
        //自定义传送内容
        Message.Builder msg = Message.newBuilder();
        msg.setMsgContent(title);
        msg.addExtra("args", args.toString());

        JPushClient jpushClient = new JPushClient(secretKey, appKey, 3);
        PushPayload.Builder builder = PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setMessage(msg.build())
                .setOptions(Options.newBuilder().setApnsProduction(false).setTimeToLive(86400).build());
        if(messageType!=0){
            builder.setNotification(Notification.android(title,title, null));
        }
        if(tokenList.size()==0){
            builder.setAudience(Audience.all());
        }else{
            builder.setAudience(Audience.registrationId(tokenList));
        }
        payload = builder.build();
        jpushClient.sendPush(payload);
    }
}
